/**
 * 抖音店铺评分数据记录侧边栏组件
 */

import { StyleProvider } from "@ant-design/cssinjs"
import { FormOutlined } from "@ant-design/icons"
import cssText from "data-text:~/assets/css/dataScreenV2.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import ky from "ky"
import moment from "moment"
import type {
  PlasmoCSConfig,
  PlasmoGetInlineAnchor,
  PlasmoGetShadowHostId
} from "plasmo"
import React, { useEffect, useState } from "react"

import { usePort } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/dist/hook"

import { ThemeProvider } from "~theme"
import DyShopScoreDataDetailModal from "~ui_components/DyShopScoreDataDetailModal"
import { _callApi } from "~utils/tools"

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 抖音抖店商家体验分页面
    "https://fxg.jinritemai.com/ffa/eco/experience-score*"
  ],
  run_at: "document_start"
  // all_frames: true
}

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

// 注入的shadow dom的id
export const HOST_ID = "dy-shop-score-tool"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

// export const getRootContainer = () => document.getElementById("app")
export const getInlineAnchor: PlasmoGetInlineAnchor = async () => {
  return {
    element: document.querySelector("div[class^='nav-menu_rightBar']"),
    insertPosition: "afterbegin"
  }
}

// 组件定义
const DyShopScoreToolbar: React.FC = () => {
  // 评分数据处理port
  const scoreData = usePort("dyShopScoreData")
  // 数据完整性百分比
  const [dataCompleteRate, setDataCompleteRate] = useState("0")
  // 用户是否登录
  const [userLogin] = useStorage("isLogin", false)
  const [showDetailModal, setShowDetailModal] = useState<boolean>(false)
  // 异常信息记录
  const [exceptionTxt, setExceptionTxt] = useState("")

  // 网络请求拦截事件响应
  // window hijackEvent响应方法
  const eventFunc = (
    event: CustomEvent<{
      url: string
      response: any
    }>
  ) => {
    // api地址过滤
    const matchUrls = [
      `^https://fxg.jinritemai.com/governance/shop/experiencescore/getOverviewByVersion`,
      `^https://fxg.jinritemai.com/governance/shop/experiencescore/getSubScoreNew`
    ]
    const matchRes = matchUrls.some((url) => {
      const regUrl = new RegExp(url)
      return regUrl.test(event.detail.url)
    })
    if (matchRes) {
      scoreData.send({ ...event.detail, action: "inspect" })
      // 通知删除iframe
      window.dispatchEvent(new Event("iframeDelete"))
    }
  }

  // 通过IFrame捕获评分数据
  const handleFetchDataByIFrame = (nodeId: undefined | number) => {
    return new Promise(async (resolve) => {
      const detailUrl = nodeId
        ? `https://fxg.jinritemai.com/ffa/eco/experience-score/detail?nodeId=${nodeId}`
        : "https://fxg.jinritemai.com/ffa/eco/experience-score"
      // 使用iframe获取
      const iframe = document.createElement("iframe")
      // 将 iframe 移动到视口之外
      iframe.style.position = "absolute"
      iframe.style.left = "-9999px"
      iframe.src = detailUrl
      iframe.id = "fetch-iframe-" + (nodeId || "overview")
      // 处理 iframe 加载错误
      iframe.onerror = () => {
        resolve(new Error("Failed to load iframe"))
      }

      // 拦截结束事件处理
      const deleteIframeEventHandler = () => {
        iframe.remove()
        window.removeEventListener("iframeDelete", deleteIframeEventHandler)
        return resolve(true)
      }

      window.addEventListener("iframeDelete", deleteIframeEventHandler)

      document.body.appendChild(iframe)
    })
  }

  // 获取数据键值总量
  const getKeysCount = async () => {
    const { data } = await _callApi("getKeysCountForDss", {})
    scoreData.send({ action: "setKeys", data: data || 0 })
  }

  // 挂载事件监听
  useEffect(() => {
    // 获取数据键总量
    getKeysCount().then()
    // 挂载ui到服务
    scoreData.send({ action: "amount" })
    // 监听hijackEvent事件
    window.addEventListener("hijackEvent", eventFunc)
    return () => {
      // 卸载事件监听
      window.removeEventListener("hijackEvent", eventFunc)
    }
  }, [])

  // 数据抓取按钮触发方法
  const handleCaptureData = async () => {
    // 捕获参数列表
    const params = [undefined, 108, 205, 309]
    // 循环请求数据
    for (let i = 0; i < params.length; i++) {
      await handleFetchDataByIFrame(params[i])
      console.log("抓取数据完成", params[i])
    }
  }

  // 数据显示对话框点击显示
  const handleShowDetailModal = () => {
    setShowDetailModal(true)
  }

  // 数据显示对话框关闭方法
  const handleClose = () => {
    setShowDetailModal(false)
  }

  // 数据清空方法
  const handleClear = () => {
    scoreData.send({
      action: "clear"
    })
  }

  useEffect(() => {
    const rate = scoreData.data?.rate || "0"
    // 数据完整率
    setDataCompleteRate(rate)
    // 异常信息记录 对比更新日期
    // 评分日期
    const scoreDate = scoreData.data?.scoreDate || ""
    // 细节日期
    const detailDate = scoreData.data?.detailDate || ""
    const isCurrentDate = (date: string) => {
      return moment(date).isSame(moment(), "date")
    }
    // 判断是否有和当前日期相同
    if (scoreDate === "" && detailDate === "") {
      // 没有日期记录
      setExceptionTxt("没有数据记录")
    } else if (!isCurrentDate(scoreDate) && !isCurrentDate(detailDate)) {
      // 两个日期都是非当天，提示异常信息
      setExceptionTxt("当前数据非当天数据,原因:[平台未更新]")
    } else if (!moment(scoreDate).isSame(moment(detailDate), "date")) {
      // 两个数据日期不一致，提示异常信息
      setExceptionTxt("当前数据不同步,原因:[部分数据未更新]")
    } else {
      setExceptionTxt("")
    }
  }, [scoreData.data])

  return (
    <ThemeProvider>
      <StyleProvider container={document.getElementById(HOST_ID).shadowRoot}>
        {userLogin ? (
          <div className={"dy-shop-score-tool-wrapper"}>
            <div className={"button-item"} onClick={handleShowDetailModal}>
              <FormOutlined />
            </div>
            {/*文字描述*/}
            <div className={"button-text"}>
              <span>评分数据</span>
            </div>
            {/*数据完整度*/}
            <div className={"button-tip"}>
              <span>{dataCompleteRate}%</span>
            </div>
          </div>
        ) : null}
        <DyShopScoreDataDetailModal
          shopType={"dy"}
          keys={scoreData?.data?.keysList}
          showDetailModal={showDetailModal}
          handleClose={handleClose}
          dataObject={scoreData?.data?.data}
          dataCompleteRate={dataCompleteRate}
          exceptionTxt={exceptionTxt}
          handleClear={handleClear}
          handleCapture={handleCaptureData}
        />
      </StyleProvider>
    </ThemeProvider>
  )
}

export default DyShopScoreToolbar
